﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace WeChatGZHTextExtractor
{
    public static class HttpHelper
    {
        /// <summary>
        /// Get模式的获取数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="formData"></param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get,
            };

            request.Headers.Add("Cookie", new List<string> { "SUID=E101FF703108990A000000005ABF869C" });

            var res = httpClient.SendAsync(request);
            res.Wait();

            var resp = res.Result;
            Task<string> temp = resp.Content.ReadAsStringAsync();
            temp.Wait();

            return temp.Result;
        }

        /// <summary>
        /// Post模式请求数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="formData"></param>
        /// <returns></returns>
        public static string HttpPost(string url, object obj)
        {
            string charset = "UTF-8";
            string mediaType = "application/x-www-form-urlencoded";

            string tokenUri = url;
            var client = new HttpClient();
            HttpContent content = new StringContent(JsonConvert.SerializeObject(obj));
            content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
            content.Headers.ContentType.CharSet = charset;

            var res = client.PostAsync(tokenUri, content);
            res.Wait();
            HttpResponseMessage resp = res.Result;

            var res2 = resp.Content.ReadAsStringAsync();
            res2.Wait();

            string token = res2.Result;
            return token;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="file_name"></param>
        internal static void HttpDownload(string url, string file_name)
        {
            HttpDownload(url, null, file_name);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ref_url"></param>
        /// <param name="file_name"></param>
        internal static void HttpDownload(string url, string ref_url, string file_name)
        {
            var httpclient = new HttpClient();

            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get,
            };

            if (!string.IsNullOrEmpty(ref_url))
                request.Headers.Referrer = new Uri(ref_url);

            var response_message = httpclient.SendAsync(request).Result;
            var response_stream = response_message.Content.ReadAsStreamAsync().Result;

            Stream file_stream = new FileStream(file_name, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = response_stream.Read(bArr, 0, bArr.Length);
            while (size > 0)
            {
                file_stream.Write(bArr, 0, size);
                size = response_stream.Read(bArr, 0, bArr.Length);
            }
            file_stream.Close();
            response_stream.Close();
        }

        /// <summary>
        /// 创建上层文件夹
        /// </summary>
        /// <param name="path"></param>
        public static void CreateParentDir(string path)
        {
            var parent = Directory.GetParent(path).FullName;
            if (!Directory.Exists(parent))
                Directory.CreateDirectory(parent);
        }

        /// <summary>
        /// 新建一个本地文件名
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string NewLocalFileName(string url)
        {
            var ext = Path.GetExtension(url);
            ext = string.IsNullOrEmpty(ext) ? ".jpg" : ext;
            return Guid.NewGuid().ToString("N") + ext;
        }
    }
}
